/*
 * @Author: “ygnnli” “1585923072@qq.com”
 * @Date: 2024-08-01 19:51:50
 * @LastEditors: “ygnnli” “1585923072@qq.com”
 * @LastEditTime: 2024-08-02 12:08:59
 * @FilePath: /110/40/consumer_producor/Thread.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#ifndef __THREAD_HPP__
#define __THREAD_HPP__

#include <iostream>
#include <string>
#include <unistd.h>
#include <functional>
#include <pthread.h>

namespace ThreadModule
{
    //调用”其他“线程的方法
    using func_t = std::function<void(std::string &)>;

    class Thread
    {
    public:
        // 线程执行任务
        void Excute()
        {
            _func(_threadname);
        }

    public:
        Thread(func_t func, std::string name = "none-name")
            : _func(func), _threadname(name), _stop(true)
        {
        }

        
        static void *threadroutine(void *args) // 类成员函数，形参是有this指针的！！
        {
            Thread *self = static_cast<Thread *>(args);
            self->Excute();
            return nullptr;
        }
        //启动线程
        bool Start()
        {
            //创建线程
            int n = pthread_create(&_tid, nullptr, threadroutine, this);
            if (!n)
            {
                _stop = false;
                return true;
            }
            else
            {
                return false;
            }
        }
        //分离线程
        void Detach()
        {
            if (!_stop)
            {
                pthread_detach(_tid);
            }
        }
        //等待线程结束
        void Join()
        {
            if (!_stop)
            {
                pthread_join(_tid, nullptr);
            }
        }
        //获取线程名称
        std::string name()
        {
            return _threadname;
        }
        //停止线程
        void Stop()
        {
            _stop = true;
        }
        ~Thread() {}

    private:
        pthread_t _tid;
        std::string _threadname;
        func_t _func;
        bool _stop;
    };
} // namespace ThreadModule

#endif